package org.spiderflow.selenium.driver;

import cn.hutool.core.io.FileUtil;
import org.openqa.selenium.WebDriver;
import org.spiderflow.model.SpiderNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

/**
 * phantomJs
 */
@Component
public class PhantomJsDriverProvider implements DriverProvider {


    @Value("${selenium.driver.phantomJs:null}")
    private String phantomJsDriverPath;
    @Value("${selenium.driver.phantomJsPath:null}")
    private String phantomJsDriverJsPath;

    @Override
    public String support() {
        return phantomJsDriverPath != null ? "phantomJs" : null;
    }

    @Override
    public WebDriver getWebDriver(SpiderNode node, String proxyStr) {
        System.setProperty("webdriver.phantomJs.driver", phantomJsDriverPath);
        System.setProperty("webdriver.phantomJs.jsPath", phantomJsDriverJsPath);
        File file = FileUtil.file(phantomJsDriverJsPath);
        if (!file.exists()) {
            InputStream inputStream = PhantomJsDriverProvider.class.getClassLoader().getResourceAsStream("phantom/phantomWebDriver.js");
            FileUtil.writeFromStream(inputStream, file);
        }
        PhantomJsDriver phantomJsDriver = new PhantomJsDriver();
        return phantomJsDriver;
    }
}
